Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.

In [1]:
#import libraries
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.gridspec as gridspec
import numpy.random as rnd
import pickle
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.contrib.layers as layers

Step 0: Load The Data

In [2]:
# Load pickled data
training_file = 'data/train.p'
validation_file = 'data/valid.p'
testing_file = 'data/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [3]:
# Number of training examples
n_train = X_train.shape[0]

# Number of validation examples
n_validation = X_valid.shape[0]

# Number of testing examples.
n_test = X_test.shape[0]

# What's the shape of a traffic sign image?
image_shape = X_train[0].shape

# How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of validation examples =", n_validation)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Number of validation examples = 4410
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [4]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.

def plot_random_samples(images, labels, n=10):
    '''A function to plot random samples for 
       labels 0-42 in a horizontal grid'''
    for label in np.unique(labels):
        ids, = np.where(labels==label)
        sample_ids = rnd.randint(0,len(ids),n)
        samples = images[sample_ids]
        
        gs = gridspec.GridSpec(1,10,top=1., bottom=0., right=1., left=0., hspace=0.05,wspace=0.05)
        for index,g in enumerate(gs):
            ax = plt.subplot(g)
            ax.set_title(label)
            ax.imshow(samples[index])
            ax.set_xticks([])
            ax.set_yticks([])        
        plt.show()

plot_random_samples(X_train, y_train)
In [5]:
## Plot the histogrm of all images.
## The histogram is computed by averaging pixel intensities over all three channels.

def hist_img_data(X):
    plt.hist(np.mean(X,axis=3).flatten(),bins=range(256),color='k',density=True)
    plt.xlabel('intensity(I)')
    plt.ylabel('fraction of all pixels with intensity =(I)')
    plt.show()
    
    #Cumulative histogram
    plt.hist(np.mean(X,axis=3).flatten(),bins=range(256),color='r',density=True,cumulative=True, histtype='step')
    plt.xlabel('intensity(I)')
    plt.xticks([50,100,150,200,250],['very dark', 'dark', 'medium','light','very light'])
    plt.ylabel('fraction of all pixels with intensity <=(I)')
    plt.show()

hist_img_data(X_train)
In [6]:
## Plot frequency of each type of traffic sign in the training data.
def hist_labels(datasets=None,ylabels=None):
    fig = plt.figure(figsize=(16,4))
    

    for i in range(len(datasets)):
        axis = fig.add_subplot(1,3,i+1)
        axis.hist(datasets[i],bins=range(n_classes+1),color='k')
        plt.ylabel('#{} Samples'.format(ylabels[i]))  
        plt.xlabel('Traffic Sign ID')

    fig.subplots_adjust(wspace=0.5)
    plt.suptitle("Sample Distribution by Class")    
    plt.show()
    
hist_labels(datasets = [y_train,y_valid, y_test],ylabels  = ['train','valid','test'])

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [7]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.

import cv2
def hist_equalize(X):
    '''A function to equalize the intensities across all 3 channels'''
    for i in range(X.shape[0]):
        img_rgb = X[i,:,:,:]
        img_yuv = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2YUV)
        img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
        X[i,:,:,:] = cv2.cvtColor(img_yuv,cv2.COLOR_YUV2RGB)        
    return X

X_train = hist_equalize(X_train)
X_valid = hist_equalize(X_valid)
X_test  = hist_equalize(X_test)
In [8]:
#Plot the histogram after equalizing the intensities
hist_img_data(X_train)
In [9]:
#Plot the samples from histogram equalized images
plot_random_samples(X_train, y_train)
In [10]:
#Define functions that implement data augmentation here

MIN_ROTATION = -10.0
MAX_ROTATION =  10.0

MIN_OFFSET = -2
MAX_OFFSET = 2

MIN_PIXEL_POSITION = 12
MAX_PIXEL_POSITION = 20



def apply_random_affine(img,n):
    '''Rotate and translate images'''
    # Allocate an array for holding all transformed images.
    output = np.zeros(shape=[n,*img.shape],dtype=img.dtype)
    
    # Generate random centers and angles for rotation.
    angles = (MAX_ROTATION-MIN_ROTATION) * np.random.random(n) + MIN_ROTATION
    centers= np.random.randint(MIN_PIXEL_POSITION,MAX_PIXEL_POSITION+1,size=[n,2])
    
    # Generate random offsets for translation.
    offsets = np.random.randint(MIN_OFFSET,MAX_OFFSET+1,size=[n,2])
    
    # Generate transformed copies of input image.
    for i in range(n):
        M_rotate = cv2.getRotationMatrix2D(tuple(centers[i]),angles[i],1)
        tmp = cv2.warpAffine(img,M_rotate,None)
        
        M_translate = np.float32([[1, 0, offsets[i,0]], [0, 1, offsets[i,1]]])
        output[i] = cv2.warpAffine(tmp,M_translate,img.shape[:2])
    
    return output
        

def add_variants(X,y,n_copies):
    
    #Initialize output dataset with original data.
    X_out = np.copy(X)
    y_out = np.copy(y)
    
    # Generate copies for every image in the original dataset.
    # Append these copies and corresponding labels to output dataset.
    m = len(X)
    for i in range(m):
        variant_data = apply_random_affine(X[i],n_copies)
        X_out = np.vstack((X_out,variant_data))

        variant_labels = np.array([y[0]]*n_copies,dtype=y.dtype)
        y_out = np.concatenate((y_out,variant_labels))
    
    return (X_out,y_out)
          
def augment_data(X,y,MIN_EXAMPLE_COUNT = 1000):
    # Get sample count for every class label.
    # For np.histogram to work correctly with 0-based labels,
    # the number for bins has to be 1 more than the number of
    # classes.
    counts, labels = np.histogram(y,bins=range(n_classes+1))
    
    
    # Initilize empty output arrays. These will be filled with
    # original and transformed samples.
    data_shape = X.shape[1:]
    data_type  = X.dtype
    
    label_shape = y.shape[1:]
    label_type  = y.dtype
    
    X_out = np.empty(shape=[0,*data_shape],dtype=data_type)
    y_out = np.empty(shape=[0,*label_shape],dtype=label_type)
    
    
    # For every class, generate an appropriate number of synthetic samples.
    # np.histogram() above will generate one extra label
    # that we don't iterate over.
    
    for label in labels[:-1]:
        X_label = X[y==label]
        y_label = y[y==label]
        
        n_orig = len(y_label)
        
        if(counts[label] < 0.5 * MIN_EXAMPLE_COUNT):
            n_copies = MIN_EXAMPLE_COUNT//counts[label]
            X_label,y_label = add_variants(X_label,y_label,n_copies)
            
        n_total = len(y_label)
        
        X_out = np.concatenate((X_out,X_label))
        y_out = np.concatenate((y_out,y_label))
            
        print("Class label {}, original sample count {}, updated sample count {}"\
              .format(label,n_orig,n_total))
        
    return (X_out, y_out)
In [11]:
#Augment the data up to at least 5000 variants for each label
X_train, y_train = augment_data(X_train,y_train,MIN_EXAMPLE_COUNT=5000)
Class label 0, original sample count 180, updated sample count 5040
Class label 1, original sample count 1980, updated sample count 5940
Class label 2, original sample count 2010, updated sample count 6030
Class label 3, original sample count 1260, updated sample count 5040
Class label 4, original sample count 1770, updated sample count 5310
Class label 5, original sample count 1650, updated sample count 6600
Class label 6, original sample count 360, updated sample count 5040
Class label 7, original sample count 1290, updated sample count 5160
Class label 8, original sample count 1260, updated sample count 5040
Class label 9, original sample count 1320, updated sample count 5280
Class label 10, original sample count 1800, updated sample count 5400
Class label 11, original sample count 1170, updated sample count 5850
Class label 12, original sample count 1890, updated sample count 5670
Class label 13, original sample count 1920, updated sample count 5760
Class label 14, original sample count 690, updated sample count 5520
Class label 15, original sample count 540, updated sample count 5400
Class label 16, original sample count 360, updated sample count 5040
Class label 17, original sample count 990, updated sample count 5940
Class label 18, original sample count 1080, updated sample count 5400
Class label 19, original sample count 180, updated sample count 5040
Class label 20, original sample count 300, updated sample count 5100
Class label 21, original sample count 270, updated sample count 5130
Class label 22, original sample count 330, updated sample count 5280
Class label 23, original sample count 450, updated sample count 5400
Class label 24, original sample count 240, updated sample count 5040
Class label 25, original sample count 1350, updated sample count 5400
Class label 26, original sample count 540, updated sample count 5400
Class label 27, original sample count 210, updated sample count 5040
Class label 28, original sample count 480, updated sample count 5280
Class label 29, original sample count 240, updated sample count 5040
Class label 30, original sample count 390, updated sample count 5070
Class label 31, original sample count 690, updated sample count 5520
Class label 32, original sample count 210, updated sample count 5040
Class label 33, original sample count 599, updated sample count 5391
Class label 34, original sample count 360, updated sample count 5040
Class label 35, original sample count 1080, updated sample count 5400
Class label 36, original sample count 330, updated sample count 5280
Class label 37, original sample count 180, updated sample count 5040
Class label 38, original sample count 1860, updated sample count 5580
Class label 39, original sample count 270, updated sample count 5130
Class label 40, original sample count 300, updated sample count 5100
Class label 41, original sample count 210, updated sample count 5040
Class label 42, original sample count 210, updated sample count 5040
In [17]:
# Normalize the pixel values for train, validate and test sets
# Calculate per-channel pixel mean and std deviation.

pixel_means   = np.mean(X_train,axis=(0,1,2),dtype=np.float32)
pixel_stddevs = np.std(X_train,axis=(0,1,2),dtype=np.float32)

X_train_norm =  X_train - pixel_means
X_train_norm =  X_train_norm / (pixel_stddevs + 1e-6) #avoid division by 0

X_valid_norm = X_valid - pixel_means
X_valid_norm = X_valid_norm / (pixel_stddevs + 1e-6)  #avoid division by 0

X_test_norm = X_test - pixel_means
X_test_norm = X_test_norm / (pixel_stddevs + 1e-6)    #avoid division by 0

Model Architecture

In [18]:
# Wrappers for conv, maxpool, flatten and dense layers.

def conv(X,W,b,stride=1):
    out = tf.nn.conv2d(X,W,[1,stride,stride,1],padding='VALID')
    out = tf.nn.bias_add(out,b)
    return tf.nn.relu(out)


def maxpool(X,k,s):
    return tf.nn.max_pool(X,ksize=[1,k,k,1],strides=[1,s,s,1],padding='VALID')

def flatten(X):
    return layers.flatten(X)

def dense(x,W,B,squash=True):
    out = tf.matmul(x,W)
    out = tf.add(out,B)
    
    if squash == True:
        out = tf.nn.relu(out)
    return out
In [19]:
# Define hyper-parameters.
epochs = 130
batch_size = 128
learning_rate = 0.001
dropout_probability = 0.3
In [20]:
# Build LeNet like convolution network.

# Mean and std. deviation for randomly initilized parameters.
mu = 0
sigma = 0.1

# Define input plaeholders.
X = tf.placeholder(tf.float32,[None,32,32,3])
y = tf.placeholder(tf.uint8,[None])
keep_prob = tf.placeholder(tf.float32)

# Define parameters (weights and biases)
params = {
    # 5x5 convolution, input depth 3, output depth 6.
    'conv1':{
        'weights':tf.Variable(tf.truncated_normal([5,5,3,6],mu,sigma)),
        'biases' :tf.Variable(tf.zeros([6])),
        'stride':1
    },
    
    # 2x2 pooling
    'pool1':{
        'kernel_sz':2,
        'stride':2
    },
    
    # 5x5 convolution, input depth 6, output depth 16.
    'conv2':{
        'weights':tf.Variable(tf.truncated_normal([5,5,6,16],mu,sigma)),
        'biases':tf.Variable(tf.zeros([16])),
        'stride':1
    },
    
    # 2x2 pooling
    'pool2':{
        'kernel_sz':2,
        'stride':2
    },
    
    # 400 -> 120 dense layer
    'dense1':{
        'weights':tf.Variable(tf.truncated_normal([400,120],mu,sigma)),
        'biases':tf.Variable(tf.zeros([120]))
    },
    
    # 120 -> 84
    'dense2':{
        'weights':tf.Variable(tf.truncated_normal([120,84],mu,sigma)),
        'biases':tf.zeros(([84]))
    },
    
    # 84 -> 43
    'dense3':{
        'weights':tf.Variable(tf.truncated_normal([84,43],mu,sigma)),
        'biases':tf.zeros(([43]))
    }   
}

conv1_out = conv(X,params['conv1']['weights'],params['conv1']['biases'],params['conv1']['stride'])
pool1_out = maxpool(conv1_out,params['pool1']['kernel_sz'],params['pool1']['stride'])


conv2_out = conv(pool1_out,params['conv2']['weights'],params['conv2']['biases'],params['conv2']['stride'])
pool2_out = maxpool(conv2_out,params['pool2']['kernel_sz'],params['pool2']['stride'])


flat_out  = flatten(pool2_out)

fc1_out   = dense(flat_out,params['dense1']['weights'],params['dense1']['biases'])
fc1_out = tf.nn.dropout(fc1_out,keep_prob)
    
fc2_out   = dense(fc1_out,params['dense2']['weights'],params['dense2']['biases'])
fc2_out = tf.nn.dropout(fc2_out,keep_prob)
    
fc3_out   = dense(fc2_out,params['dense3']['weights'],params['dense3']['biases'],squash=False)
logits = fc3_out

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [22]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.

one_hot_y = tf.one_hot(y,n_classes,on_value=1,off_value=0)

# Define cost function (minimization objective) and minimization algorithm.
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=one_hot_y)
training_loss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate)
optimization = optimizer.minimize(training_loss)

# Define accuracy.
correct_predictions = tf.equal(tf.argmax(logits,1),tf.argmax(one_hot_y,1))
accuracy_calculation = tf.reduce_mean(tf.cast(correct_predictions,tf.float32))
In [23]:
# Define evalution function.
def evaluate(sess,X_data,y_data):
    num_examples = X_data.shape[0]
    
    net_accuracy = 0.0;
    n_batches = num_examples // batch_size
    for offset in range(0,num_examples,batch_size):
        X_batch = X_data[offset:offset+batch_size]
        y_batch = y_data[offset:offset+batch_size]
        
        batch_accuracy = sess.run(accuracy_calculation,feed_dict={X:X_batch,y:y_batch,keep_prob:1.0})
        
        net_accuracy += batch_accuracy
    
    return net_accuracy / n_batches
In [24]:
# Define training function
from sklearn.utils import shuffle
from tqdm import tqdm

def train(sess):
    sess.run(tf.global_variables_initializer())
    
    for e in tqdm(range(epochs)):
        global X_train, X_train_norm, y_train 
        X_train, X_train_norm, y_train = shuffle(X_train, X_train_norm,y_train)
        for offset in range(0,n_train,batch_size):
            X_batch = X_train_norm[offset:offset+batch_size]
            y_batch = y_train[offset:offset+batch_size]

            sess.run(optimization,feed_dict={X:X_batch,y:y_batch,keep_prob:1-dropout_probability})

        if (e+1) % 10 == 0:
            train_accuracy = evaluate(sess,X_train_norm,y_train)
            valid_accuracy = evaluate(sess,X_valid_norm,y_valid)
            print("Epochs {}, training accuracy {:.3f}, validation accuracy {:.3f}"\
                .format(e+1,train_accuracy,valid_accuracy))
In [25]:
model_file_prefix = './saved_model'
def run_training(sess):
    print("Training started!")
    train(sess)
    print("Training completed!")
    print("Evaluating model on test data...")
    print("Test accuracy {:.3f}".format(evaluate(sess,X_test_norm,y_test)))

    print("Saving model data to file...")
    saver = tf.train.Saver()
    saver.save(sess,model_file_prefix)
    print("Model saved!")
In [26]:
# Run training or load exiting model.
import os
use_existing = False

session = tf.Session(config=tf.ConfigProto(log_device_placement=True))

if use_existing == False:
    run_training(session)

elif (use_existing == True) and (not os.path.isfile(model_file_prefix+'.meta')):
    print("Saved model file doens't exist! Running training again...")
    run_training(session)

else:
    #Load saved model.
    print("Reloading existing model...")
    saver = tf.train.Saver()
    saver.restore(session,tf.train.latest_checkpoint('.') )
    print("Model loading finished!")
Training started!
  8%|▊         | 10/130 [00:47<11:02,  5.52s/it]
Epochs 10, training accuracy 0.938, validation accuracy 0.952
 15%|█▌        | 20/130 [01:33<09:56,  5.43s/it]
Epochs 20, training accuracy 0.969, validation accuracy 0.977
 23%|██▎       | 30/130 [02:18<09:02,  5.43s/it]
Epochs 30, training accuracy 0.977, validation accuracy 0.988
 31%|███       | 40/130 [03:02<08:05,  5.40s/it]
Epochs 40, training accuracy 0.982, validation accuracy 0.992
 38%|███▊      | 50/130 [03:47<07:13,  5.42s/it]
Epochs 50, training accuracy 0.986, validation accuracy 1.001
 46%|████▌     | 60/130 [04:31<06:15,  5.36s/it]
Epochs 60, training accuracy 0.987, validation accuracy 0.999
 54%|█████▍    | 70/130 [05:16<05:27,  5.46s/it]
Epochs 70, training accuracy 0.989, validation accuracy 0.993
 62%|██████▏   | 80/130 [06:01<04:33,  5.46s/it]
Epochs 80, training accuracy 0.988, validation accuracy 0.997
 69%|██████▉   | 90/130 [06:46<03:36,  5.42s/it]
Epochs 90, training accuracy 0.988, validation accuracy 0.997
 77%|███████▋  | 100/130 [07:31<02:41,  5.38s/it]
Epochs 100, training accuracy 0.991, validation accuracy 1.005
 85%|████████▍ | 110/130 [08:15<01:47,  5.38s/it]
Epochs 110, training accuracy 0.994, validation accuracy 1.009
 92%|█████████▏| 120/130 [09:01<00:54,  5.49s/it]
Epochs 120, training accuracy 0.992, validation accuracy 1.001
100%|██████████| 130/130 [09:46<00:00,  5.41s/it]
Epochs 130, training accuracy 0.989, validation accuracy 0.999
Training completed!
Evaluating model on test data...

Test accuracy 0.955
Saving model data to file...
Model saved!
In [27]:
# Compute key metrics.
from tqdm import tqdm
def compute_key_metrics(sess,X_data,y_data):
    confusion_matrix = np.zeros([n_classes,n_classes],np.int32)
    predicted_labels = np.zeros_like(y_data)
    
    n_examples = X_data.shape[0]
    for offset in tqdm(range(0,n_examples,batch_size)):
        X_batch = X_data[offset:offset+batch_size]
        y_batch = y_data[offset:offset+batch_size]
        
        y_predicted = sess.run(tf.argmax(logits,1),feed_dict={X:X_batch, y:y_batch, keep_prob:1.0})
        np.add.at(confusion_matrix,[y_batch,y_predicted],1)
        
        predicted_labels[offset:offset+batch_size] = y_predicted
    
    
    # True positives live on the main diagonal. Extract them.
    true_postives = confusion_matrix[[range(n_classes)],[range(n_classes)]]
  
    # For false positives take column-wise sum excluding the row of the target class.
    false_positives = np.sum(confusion_matrix,axis=0) - true_postives
    
    # For false negatives take row-wise sum exclding the column of the target class.
    false_negatives = np.sum(confusion_matrix,axis=1) - true_postives
    
    # True negatives are all values in the matrix excluding the row and column of a class.
    true_negatives  = np.sum(confusion_matrix) - (true_postives+false_positives+false_negatives)
    
    precision = np.squeeze(true_postives / (true_postives+false_positives+1e-6))
    recall    = np.squeeze(true_postives / (true_postives+false_negatives+1e-6))
    specificity = np.squeeze(true_negatives / (true_negatives+false_positives+1e-6))
    
    return {'confmat':confusion_matrix, 'predicted_labels':predicted_labels, 'precision':precision,'recall':recall, 'specificity':specificity}
In [28]:
metrics = compute_key_metrics(session,X_test_norm,y_test)
100%|██████████| 99/99 [00:04<00:00, 19.48it/s]
In [29]:
#Read in sign names from signnames.csv
import pandas
sign_names = pandas.read_csv('signnames.csv')
sign_names = sign_names.as_matrix()

predicted_labels = metrics['predicted_labels']
In [30]:
# Plot first 100 mis-classified images 
misclassified_idx = np.where(np.not_equal(y_test,metrics['predicted_labels']))
M = X_test[misclassified_idx][:100]

gs = gridspec.GridSpec(25, 4,top=8., bottom=0., right=2., left=0., hspace=1,wspace=0.05)

for i,g in enumerate(gs):
    ax = plt.subplot(g)
    ax.imshow(M[i])
    ax.set_title("Actual {}\nPredicted {}".format(sign_names[y_test[misclassified_idx][i]][1],
                                                        sign_names[predicted_labels[misclassified_idx][i]][1]))
    ax.set_xticks([])
    ax.set_yticks([])
    
plt.show()
In [31]:
# Plot precision and recall for all classes
plt.bar(range(n_classes),metrics['precision'])
plt.title('precision')
plt.show()
plt.bar(range(n_classes),metrics['recall'])
plt.title('recall')
plt.show()
In [32]:
# Print low precision and low recall classes
low_precision_classes = np.argsort(metrics['precision'])[:3]
low_recall_classes    = np.argsort(metrics['recall'])[:3]
print("Low precision classes:",low_precision_classes)
print("Low recall classes:",low_recall_classes)
Low precision classes: [27 24 21]
Low recall classes: [30  5 20]
In [33]:
# Get a copy of the confusion matrix excluding true positives.
conf_mat = np.copy(metrics['confmat'])
np.fill_diagonal(conf_mat,0)

# For each class with low precision get class that causes most false positives.
false_positive_classes = np.argmax(conf_mat[:,low_precision_classes], axis=0)
print("False positive classes:",false_positive_classes)

# For each class with low recall get class that causes most false negatives.
false_negative_classes = np.argmax(conf_mat[low_recall_classes,:],axis=1)
print("False negative classes:",false_negative_classes)
False positive classes: [25 29 18]
False negative classes: [11  2 28]
In [34]:
# Plot and compare actual and predicted image classes with low precision 
for i in range(len(low_precision_classes)):
    # Get misclassified samples from false positive class.
    fp_idx = np.logical_and(np.squeeze(y_test==false_positive_classes[i]),
                                np.squeeze(predicted_labels== low_precision_classes[i]))
                                
    fp_samples = X_test[fp_idx]
    
    # Get (representative) samples from the target class.
    target_idx = np.where(y_test == low_precision_classes[i] )
    target_samples = X_test[target_idx]
    
    print("Actual class:",sign_names[false_positive_classes[i]])
    plot_random_samples(fp_samples,8)
    print("Predicted as class:",sign_names[low_precision_classes[i]])
    plot_random_samples(target_samples,8)
    print("\n\n")
Actual class: [25 'Road work']
Predicted as class: [27 'Pedestrians']


Actual class: [29 'Bicycles crossing']
Predicted as class: [24 'Road narrows on the right']


Actual class: [18 'General caution']
Predicted as class: [21 'Double curve']


In [35]:
# Plot and compare actual and predicted image classes with low recall 
for i in range(len(low_recall_classes)):
    # Get misclassified samples from target class.
    target_idx = np.logical_and(np.squeeze(y_test==low_recall_classes[i]),
                                np.squeeze(predicted_labels== false_negative_classes[i]))
                                
    target_samples = X_test[target_idx]
    
    # Get (representative) samples from the false negative class.
    fp_idx = np.where(y_test == false_negative_classes[i] )
    fp_samples = X_test[fp_idx]
    
    print("Actual class:",sign_names[low_recall_classes[i]])
    plot_random_samples(target_samples,8)
    print("Predicted as class:",sign_names[false_negative_classes[i]])
    plot_random_samples(fp_samples,8)
    print("\n\n")
Actual class: [30 'Beware of ice/snow']
Predicted as class: [11 'Right-of-way at the next intersection']


Actual class: [5 'Speed limit (80km/h)']
Predicted as class: [2 'Speed limit (50km/h)']


Actual class: [20 'Dangerous curve to the right']
Predicted as class: [28 'Children crossing']



Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [37]:
# Load the images and plot them here.

import scipy.ndimage as ndimage
web_files=['web_images/bumpy.jpg','web_images/100kmspeed.jpg','web_images/caution-roadworks.jpg','web_images/no-vehicles.jpg','web_images/TurnRightAhead.jpg']

X_web = np.zeros([len(web_files),32,32,3],dtype=np.uint8)
y_web = np.array([22,7,25,15,33],dtype=np.uint8)

for i in range(len(web_files)):
    X_web[i] = ndimage.imread(web_files[i])
    
    plt.figure(figsize=(1,1))
    plt.imshow(X_web[i])
    plt.title(web_files[i])
    plt.show()

Predict the Sign Type for Each Image

In [38]:
# Run the predictions here and use the model to output the prediction for each image.
# Make sure to pre-process the images with the same pre-processing pipeline used earlier.

X_web = hist_equalize(X_web)
X_web_norm = X_web - pixel_means
X_web_norm = X_web_norm / (pixel_stddevs + 1e-6) #avoid division by 0
In [39]:
web_metrics = compute_key_metrics(session,X_web_norm,y_web)
100%|██████████| 1/1 [00:00<00:00, 17.67it/s]

Analyze Performance

In [40]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print("Acuracy for web images: ",np.sum(web_metrics['predicted_labels']==y_web)/len(y_web))
Acuracy for web images:  0.8

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [41]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 

top5 = session.run(tf.nn.top_k(tf.nn.softmax(logits),5), feed_dict={X:X_web_norm,y:y_web,keep_prob:1.0})
    
for i in range(len(y_web)):
    print("Actual label: {}".format(sign_names[y_web[i]]))
    print("Predicted classes and probabilities ",list(zip(top5[1][i],np.round(top5[0][i],2))))
    plt.figure(figsize=(1,1))
    plt.imshow(X_web[i])
    plt.title(web_files[i])
    plt.show()
    plt.figure(figsize=(2,2))
    plt.bar(range(5),top5[0][i])
    plt.title("Actual label: {}".format(sign_names[y_web[i]]))
    plt.xticks(range(5),sign_names[top5[1][i]],rotation='vertical')
    plt.show()
    print("-----------------------------------------------------")
Actual label: [22 'Bumpy road']
Predicted classes and probabilities  [(22, 1.0), (26, 0.0), (25, 0.0), (29, 0.0), (19, 0.0)]
-----------------------------------------------------
Actual label: [7 'Speed limit (100km/h)']
Predicted classes and probabilities  [(22, 0.83999997), (26, 0.16), (20, 0.0), (17, 0.0), (25, 0.0)]
-----------------------------------------------------
Actual label: [25 'Road work']
Predicted classes and probabilities  [(25, 1.0), (24, 0.0), (30, 0.0), (11, 0.0), (31, 0.0)]
-----------------------------------------------------
Actual label: [15 'No vehicles']
Predicted classes and probabilities  [(15, 1.0), (4, 0.0), (8, 0.0), (1, 0.0), (7, 0.0)]
-----------------------------------------------------
Actual label: [33 'Turn right ahead']
Predicted classes and probabilities  [(33, 1.0), (39, 0.0), (36, 0.0), (35, 0.0), (40, 0.0)]
-----------------------------------------------------

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.